package lxq.away3d.controller;

import away3d.containers.ObjectContainer3D;
import away3d.controllers.HoverController;
import away3d.entities.Entity;
import away3d.entities.Mesh;

import flash.display.InteractiveObject;
import flash.display.Stage;
import flash.events.MouseEvent;
import flash.geom.Vector3D;

class OrbitController extends HoverController
{
private var _interactiveSource:Stage;
private var _oldX:Float;
private var _oldY:Float;
private var _oldPan:Float;
private var _oldTitle:Float;
private var _nextDistance:Float;
private var _maxDistance:Float;
private var _minDistance:Float;
public function new(interactiveSource:Stage=null,lookAtObject:ObjectContainer3D=null,camera:Entity=null,maxDistance:Float=1000,minDistance:Float=100)
{
	_interactiveSource=interactiveSource;
	_maxDistance=maxDistance;
	_minDistance=minDistance;
	super(camera,lookAtObject,180,0,1000);
	_nextDistance=distance;
	if(interactiveSource){
	interactiveSource.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
	_interactiveSource.addEventListener(MouseEvent.MOUSE_WHEEL,onMouseWheel);
	}
}
private function onMouseDown(e:MouseEvent=null):Void{
	_oldX=e.stageX;
	_oldY=e.stageY;
	_oldPan=panAngle;
	_oldTitle=tiltAngle;
	_interactiveSource.addEventListener(MouseEvent.MOUSE_UP,onMouseUp);
	_interactiveSource.addEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
}
private function onMouseUp(e:MouseEvent=null):Void{
	_oldX=e.stageX;
	_oldY=e.stageY;
	_interactiveSource.removeEventListener(MouseEvent.MOUSE_UP,onMouseUp);
	_interactiveSource.removeEventListener(MouseEvent.MOUSE_MOVE,onMouseMove);
}
private function onMouseMove(e:MouseEvent=null):Void{
	var disx:Float=e.stageX-_oldX;
	var disy:Float=e.stageY-_oldY;
	tiltAngle=disy*.5+_oldTitle;
	panAngle=disx*.5+_oldPan;
}

private function onMouseWheel(e:MouseEvent=null):Void{
	e.delta>0?_nextDistance=distance-100:_nextDistance=distance+100;
}
public  function loop():Void{
	if(distance<_minDistance)distance=_minDistance;
	if(distance>_maxDistance)distance=_maxDistance;
	distance+=(_nextDistance-distance)*.1;
}

}